package dao

import (
	"bms/db"
	"bms/model"
	"log"
)

func GetBorrowByUserId(userId int64) (*model.Borrow, error) {
	sql := "select borrow_id,user_id,total_nums from borrows where user_id=?"
	row := db.Db.QueryRow(sql, userId)
	borrow := &model.Borrow{}
	err := row.Scan(&borrow.BorrowId, &borrow.UserId, &borrow.TotalNums)
	if err != nil {
		return nil, err
	}
	borrowItems := GetBorrowItemByBorrowId(borrow.BorrowId)
	borrow.BorrowItem = borrowItems
	return borrow, nil
}

func SaveBorrow(borrow *model.Borrow) error {
	sql := "insert into borrows(borrow_id,user_id,total_nums) values (?,?,?)"
	db.Db.Exec(sql, borrow.BorrowId, borrow.UserId, borrow.GetTotalNums())
	borrowItems := borrow.BorrowItem
	log.Println("------borrowItems--------", borrowItems)
	for _, v := range borrowItems {
		log.Println("------v--------", v)
		SaveBorrowItem(v)
		log.Println("------v--------", v)
	}
	return nil
}

func UpdateBorrowNums(borrow *model.Borrow) error {
	sql := "update borrows set total_nums=? where borrow_id=?"
	log.Println(borrow.GetTotalNums(), "2222222")
	log.Println(borrow.BorrowId, "2222222")
	_, err := db.Db.Exec(sql, borrow.GetTotalNums(), borrow.BorrowId)
	if err != nil {
		return err
	}
	return nil
}

func GetBorrow() []*model.Borrow {
	sql := "select borrow_id,user_id,total_nums from borrows"
	rows, _ := db.Db.Query(sql)
	var borrows []*model.Borrow
	for rows.Next() {
		borrow := &model.Borrow{}
		rows.Scan(&borrow.BorrowId, &borrow.UserId, &borrow.TotalNums)
		borrows = append(borrows, borrow)
	}
	return borrows
}
